package zhttp

import (
	"io"
	"net/http"
	"strings"
)

func NewClient() *Client {
	return &Client{
		cli: &http.Client{
			Transport:     nil,
			CheckRedirect: nil,
			Jar:           nil,
			Timeout:       0,
		},
	}
}

func (cli *Client) SetHttpCliArg() {
	// cli.cli.Timeout = 0
}

func (cli *Client) SetPostParams() *Client {

	return cli
}

func (cli *Client) SetPostFormParams() *Client {
	return cli
}

func (cli *Client) Ask() (bool, string) {
	switch cli.method {
	case "Get":
		return cli.get()
	case "Post":
		return cli.post()
	case "PostForm":
		return cli.postForm()
	default:
		return false, ""
	}
}

func (cli *Client) get() (bool, string) {
	resp, err := cli.cli.Get(cli.url)
	if err != nil {
		cli.err = err
		return false, ""
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	body, err := io.ReadAll(resp.Body)
	if resp.StatusCode != 200 {
		cli.err = err
		return false, ""
	}

	// err = json.Unmarshal(body, &rs)
	return true, string(body)
}

func (cli *Client) post() (bool, string) {
	resp, err := cli.cli.Post(cli.url, ApplicationJson, strings.NewReader(`{"key":"value"}`))
	if err != nil {
		cli.err = err
		return false, ""
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	body, err := io.ReadAll(resp.Body)

	if resp.StatusCode != 200 {
		cli.err = err
		return false, ""
	}

	// err = json.Unmarshal(body, &rs)
	return true, string(body)
}

func (cli *Client) postForm() (bool, string) {
	resp, err := cli.cli.PostForm(cli.url, cli.data)
	if err != nil {
		cli.err = err
		return false, ""
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)

	body, err := io.ReadAll(resp.Body)

	if resp.StatusCode != 200 {
		cli.err = err
		return false, ""
	}

	// err = json.Unmarshal(body, &rs)
	return true, string(body)
}
